//
//  SeeingThePDFViewController.m
//  EducationAdminClient
//
//  Created by kwsdzjx on 2016/11/18.
//  Copyright © 2016年 周佳兴. All rights reserved.
//

#import "SeeingThePDFViewController.h"
#import "PDFCollectionViewCell.h"
#import "QUARZView.h"
#import "NetRequest.h"
#import "JQIndicatorView.h"

@interface SeeingThePDFViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate,collectionCellDelegate,UIWebViewDelegate>//遵守协议

{
    
    UICollectionView *testCollectionView; //展示用的CollectionView
    
    CGPDFDocumentRef _docRef; //需要获取的PDF资源文件
    
}



@property(nonatomic,strong)NSMutableArray*dataArray;//存数据的数组
@property(nonatomic,copy)NSString *filePath;
@property(nonatomic,copy)UIWebView *webView;

@property(nonatomic,assign)int totalPage;//一共有多少页

@property(nonatomic, strong)JQIndicatorView *indicator;

@end

@implementation SeeingThePDFViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.http://blog.csdn.net/saw471/article/details/56676934 可参考
    [self createLeftNavBar];
    _webView = [[UIWebView alloc]init];
    _webView.delegate = self;
    _webView.scalesPageToFit = YES;
    
    _webView.backgroundColor = [UIColor clearColor];
    
    _webView.opaque = NO; // 这个东西 是影响性能的 尽量 将其 设置为 YES ；
    
    [self.view addSubview:_webView];
    
    _indicator = [[JQIndicatorView alloc] initWithType:1 tintColor:[UIColor colorWithHex:0xef5152]];
    CGPoint center = CGPointMake(KWIDTH/2, KHEIGHT/2-100);
    _indicator.center = center;
    [self.view addSubview:_indicator];
    
    NSLog(@"%@",_fileMongoArr);
    NSLog(@"%@",_mongodbIDArr);
    
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
        make.right.equalTo(self.view.mas_right);
        make.top.equalTo(self.view.mas_top);
    }];
    NSString *requestUrl;
//    NSString *requestUrl =[NSString stringWithFormat:@"%@%@",BASE_URL,GETPIC];
    if (_fileMongoArr.count>0) {

        requestUrl =[NSString stringWithFormat:@"%@%@str=%@",BASE_URL,GETPIC, _fileMongoArr[0]];
    }else{
        return;
    }
//    NSMutableDictionary *param =[NSMutableDictionary dictionary];
//    [param setObject:_fileMongoArr[0] forKey:@"str"];
//    [NetRequest requestUrl:requestUrl andParamas:param andReturnBlock:^(NSData *data, NSError *error) {
//        if(data&&!error){
//            
//            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//            NSString *documentsDirectory = [paths objectAtIndex:0];
//            NSString *sss =_nameArr[0];
//           
//           _filePath = [documentsDirectory stringByAppendingPathComponent:sss];
//                       NSFileManager *fileManager = [[NSFileManager alloc]init];
//        [fileManager createFileAtPath:_filePath contents:data attributes:nil];
//            [self loadDocument:_filePath inView:webView];
//            
//        }else{
//            
//        }
//    }];
    
    
    [_indicator startAnimating];
    [self loadDocument:requestUrl inView:_webView];

//    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    
//*** 美加专用
//    if (_fileMongoArr.count>0) {
//        [parama setObject:_fileMongoArr[0] forKey:@"id"];
//
//    }else{
//        return;
//    }
//[NetRequest requestUrl:requestUrl andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
//    if (!error&&data!=nil) {
//        
//        NSString *strData = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        
//        [self loadDocument:strData inView:_webView];
//
//    }
//}];
//    UICollectionViewFlowLayout*layout = [[UICollectionViewFlowLayout alloc]init];//UICollectionView需要在创建的时候传入一个布局参数，故在创建它之前，先创建一个布局，这里使用系统的布局就好
//    
//    layout.itemSize=self.view.frame.size;//设置CollectionView中每个item及集合视图中每单个元素的大小，我们每个视图使用一页来显示，所以设置为当前视图的大小
//    
//    [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];//设置滑动方向为水平方向，也可以设置为竖直方向
//    
//    layout.minimumLineSpacing=0;//设置item之间最下行距
//    
//    layout.minimumInteritemSpacing=0;//设置item之间最小间距
//    
//    testCollectionView= [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];//创建一个集合视图，设置其大小为当前view的大小，布局为上面我们创建的布局
//    
//    testCollectionView.pagingEnabled=YES;//设置集合视图一页一页的翻动
//    
//    [testCollectionView registerClass:[PDFCollectionViewCell class]forCellWithReuseIdentifier:@"test"];//为集合视图注册单元格
//    
//    testCollectionView.delegate=self;//设置代理
//    
//    testCollectionView.dataSource=self;//设置数据源
//    testCollectionView.backgroundColor = [UIColor clearColor];
//    
//    [self.view addSubview:testCollectionView];//将集合视图添加到当前视图上
//    
//    dispatch_queue_t queue = dispatch_queue_create("name", NULL);
//    //创建一个子线程
//    dispatch_async(queue, ^{
//        // 子线程code... ..
//        
//        [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
//        NSLog(@"GCD多线程");
//        _docRef = test(@"http://teaching.csse.uwa.edu.au/units/CITS4401/practicals/James1_files/SPMP1.pdf");//通过test函数获取PDF文件资源，test函数的实现为我们最上面的方法，当然下面又写了一遍
//        
//        [self getDataArrayValue];//获取需要展示的数据
//        [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
//
//        //回到主线程
//        dispatch_sync(dispatch_get_main_queue(), ^{//其实这个也是在子线程中执行的，只是把它放到了主线程的队列中
//            Boolean isMain = [NSThread isMainThread];
//            if (isMain) {
//                
//                [testCollectionView reloadData];
//                NSLog(@"GCD主线程");
//            }
//        });
//    });

}


-(void)loadDocument:(NSString *)documentName inView:(UIWebView *)webView
{
    //NSString *path = [[NSBundle mainBundle] pathForResource:@"-头脑风暴问题汇总" ofType:@"pdf"];
    
    // http://teaching.csse.uwa.edu.au/units/CITS4401/practicals/James1_files/SPMP1.pdf 文库测试文档
//    documentName = @"http://bailitianxia-edus.oss-cn-beijing.aliyuncs.com/2017-03-11/35-36-40%20%E6%9D%8E%E5%B2%A2%E8%99%94%E4%BD%9C%E4%B8%9A.pdf?Expires=1489206113&OSSAccessKeyId=vGYn0xGpshJEzwyt&Signature=PRC/d3lU0NOgbQcohrLUdN7ZAF4%3D";
    //NSURL *url = [NSURL fileURLWithPath:path];
    NSURL *url = [NSURL URLWithString:documentName];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    
//    [_webView loadRequest:request];

    
//    [self loadReq:nil andRequest:request];

    __weak __typeof(self)weakSelf = self;
    dispatch_queue_t queue = dispatch_queue_create("llalalala", NULL);
    dispatch_async(queue, ^{
        // 子线程code... ..
        NSString *stringBody  = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
        
        //*** GBK 解码
        if (!stringBody) {
            stringBody = [NSString stringWithContentsOfURL:url encoding:0x80000632 error:nil];
            
        }
        //*** GB18030 解码
        if (!stringBody) {
            stringBody = [NSString stringWithContentsOfURL:url encoding:0x80000631 error:nil];
            
        }

        
        //        [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:YES];
        NSLog(@"GCD多线程");
        //        [[UIApplication sharedApplication]setNetworkActivityIndicatorVisible:NO];
        //        [weakSelf createPickerTime];
        //回到主线程
        dispatch_sync(dispatch_get_main_queue(), ^{//其实这个也是在子线程中执行的，只是把它放到了主线程的队列中
            Boolean isMain = [NSThread isMainThread];
            if (isMain) {
                
                NSLog(@"GCD主线程");
                [weakSelf loadReq:stringBody andRequest:request];
            }
        });
    });
    
    
    //    NSURLResponse *response;
    
    
    //    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
//    [webView loadRequest:request];

//    if (stringBody) {
//        
//        stringBody =[stringBody stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];//替换换行符为HTML换行符
//
//        [webView loadHTMLString:stringBody baseURL:nil];
//    }else{
//        [webView loadRequest:request];
//    }
    
//    else{
//        [webView loadData:data MIMEType:response.MIMEType textEncodingName:@"UTF8" baseURL:nil];
//        
//    }
}

-(void)loadReq:(NSString *)stringBody andRequest:(NSURLRequest *)request{
    if (stringBody) {
        
        stringBody =[stringBody stringByReplacingOccurrencesOfString:@"\n" withString:@"<br>"];//替换换行符为HTML换行符
        
        [_webView loadHTMLString:stringBody baseURL:nil];
    }else{
        [_webView loadRequest:request];
    }
    
}

-(void)LeftClick:(UIButton *)btn{

    if ([self.webView canGoBack]) {
        
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}



//NSOperationQueue *queue=[NSOperationQueue mainQueue];
//
//[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//    if(data!=nil&&!connectionError){
//        NSString *stringBody = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
//        if (!stringBody) {
//            stringBody = [NSString stringWithContentsOfURL:url encoding:0x80000632 error:nil];
//            
//        }
//        //            if (!stringBody) {
//        //                stringBody = [NSString stringWithContentsOfURL:url encoding:0x80000631 error:nil];
//        //
//        //            }
//        [webView loadData:data MIMEType:response.MIMEType textEncodingName:@"UTF8" baseURL:nil];
//        
//        
//    }
//}];

//通过地址字符串获取PDF资源

CGPDFDocumentRef test(NSString *fileName) {
    
    NSURL*url = [NSURL URLWithString:fileName];
    
    CFURLRef refURL = (__bridge_retained CFURLRef)url;
    
    CGPDFDocumentRef document =CGPDFDocumentCreateWithURL(refURL);
    
    CFRelease(refURL);
    
    if(document) {
        
        return document;
        
    }else{
        
        return NULL;
        
    }
    
}


//获取所有需要显示的PDF页面

- (void)getDataArrayValue {
    
    size_t totalPages =CGPDFDocumentGetNumberOfPages(_docRef);//获取总页数
    
    self.totalPage= (int)totalPages;//给全局变量赋值
    
    NSMutableArray*arr = [NSMutableArray new];
    
    //通过循环创建需要显示的PDF页面，并把这些页面添加到数组中
    
    for(int i =1; i <= totalPages; i++) {
        
        QUARZView *view = [[QUARZView alloc]initWithFrame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height) documentRef: _docRef andPageNum:i];
        
        [arr addObject:view];
        
    }
    
    self.dataArray= arr;//给数据数组赋值
    
}

//返回集合视图共有几个分区

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView {
    
    return 1;
    
}

//返回集合视图中一共有多少个元素——自然是总页数

- (NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.totalPage;
    
}

//复用、返回cell

- (UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath {
    
    PDFCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"test"forIndexPath:indexPath];
    
    cell.cellTapDelegate=self;//设置tap事件代理
    
    cell.showView=self.dataArray[indexPath.row];//赋值，设置每个item中显示的内容
    
    return cell;
    
}

//当集合视图的item被点击后触发的事件，根据个人需求写

- (void)collectioncellTaped:(CollectionViewCell*)cell {
    
    NSLog(@"我点了咋的？");
    
}

//集合视图继承自scrollView，所以可以用scrollView 的代理事件，这里的功能是当某个item不在当前视图中显示的时候，将它的缩放比例还原

- (void)scrollViewDidEndDecelerating:(UIScrollView*)scrollView {
    
    for(UIView *view in testCollectionView.subviews) {
        
        if([view isKindOfClass:[PDFCollectionViewCell class]]) {
            
            PDFCollectionViewCell*cell = (PDFCollectionViewCell*)view;
            
            [cell.contentScrollView setZoomScale:1.0];
            
        }
        
    }
    
}


#pragma mark - UIWebViewDelegate
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    
    [_indicator startAnimating];

    //Start the progressbar..
    return YES;
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    
    [_indicator stopAnimating];

    [_webView stopLoading];

    //Stop or remove progressbar
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    //Stop or remove progressbar and show error
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
